package com.zzj.until;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;

import java.io.ByteArrayOutputStream;

/**
 * @author: zzj
 * @date: 2018/03/15
 * Time: 9:23
 */
public class ShellTool {
    public static Logger logger = LogManager.getLogger(ShellTool.class);

    public static String execShell(String cmdStr){
        String result="";
        final CommandLine cmdLine = CommandLine.parse(cmdStr);
        DefaultExecutor executor = new DefaultExecutor();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        executor.setStreamHandler(new PumpStreamHandler(baos, baos));
        executor.setExitValue(0);
        try {
            int exitValue = executor.execute(cmdLine);
            result = baos.toString("UTF-8").trim();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            e.printStackTrace();
        }
        return result;
    }

    @Test
    public void test1(){
        System.out.println(execShell("cmd /c taskkill   /pid 12600   /f  "));
    }
}
